package com.toolbox.httpRequest

import org.apache.http.HttpEntity
import org.apache.http.HttpStatus
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.BasicResponseHandler
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.impl.client.HttpClients
import org.slf4j.Logger
import org.slf4j.LoggerFactory;

class HttpClientReq {
    private  static Logger logger=LoggerFactory.getLogger(HttpClientReq.class)
    /**
     * post提交 带返回值
     * @param url 目标地址
     * @param params http post提交参数
     *  setConnectTimeout：设置连接超时时间，单位毫秒。
        setConnectionRequestTimeout：设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
        setSocketTimeout：请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
     */
    public static String doPostBack(String url, List<NameValuePair> params) {
        // 创建一个默认的HttpClient
        CloseableHttpClient  httpclient = HttpClients.createDefault()
        String result="";
        HttpPost httppost=null;
        try {
            httppost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();
            httppost.setConfig(requestConfig);
            // 将POST参数以UTF-8编码并包装成表单实体对象
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            // 创建响应处理器处理服务器响应内容
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            // 执行请求
            result = httpclient.execute(httppost, responseHandler);
        } catch (Exception e) {
            logger.error("doPostBack 接口请求一次：",e)
        } finally {
            if(httpclient!=null){
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    logger.error("doPostBack 接口请求连接关闭异常 ：",e)
                }
            }
            
        }
        return result;
    }

    /**
     * httpClient  get请求
     * @param url
     * @param json
     * @return
     *  setConnectTimeout：设置连接超时时间，单位毫秒。
        setConnectionRequestTimeout：设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
        setSocketTimeout：请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
     */
    public static String doGetByClinet(String url) throws Exception{
        // 创建一个默认的HttpClient
        CloseableHttpClient  httpclient = HttpClients.createDefault()
        StringBuilder result = new StringBuilder();
//        logger.info( "=========================url:"+url)
        try{
            HttpGet httpGet = new HttpGet(url)
            httpGet.addHeader("Content-Type", "text/html;charset=UTF-8");
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).build();
            httpGet.setConfig(requestConfig);
	 
            CloseableHttpResponse res = httpclient.execute(httpGet);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//请求相应
                    HttpEntity entity = res.getEntity();
                    if (entity != null) {
                        // 读取服务器返回的数据
                        InputStream inputStream = entity.getContent();
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                        BufferedReader reader = new BufferedReader(inputStreamReader);
                        String s;
                        while (((s = reader.readLine()) != null)) {
                            result.append(s);
                        }
                        reader.close();// 关闭输入流
                    }
            }else{
                logger.info("=========================doGetByClinet接口返回非200,返回状态为："+res.getStatusLine().getStatusCode())
                return null;
            }
        }catch (Exception e1){
            logger.error("doGetByClinet 接口请求异常：",e1)
        }finally{
            if(httpclient!=null){
                // 关闭连接,释放资源
                try {
                    httpclient.close();
                } catch (IOException e) {
                    logger.error("doGetByClinet 接口请求连接关闭异常 ：",e)
                }
            }
        }
        return result.toString();
    }

    /**
     * java get 请求
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        URL localURL = new URL(url);
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        println "HTTP Request url  is:"+url
        println "HTTP Request return  Response code is:"+httpURLConnection.getResponseCode()

        if (httpURLConnection.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }

        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }

        } finally {

            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return resultBuffer.toString();
    }

}
